<?php

/**
 * auth actions.
 *
 * @package    Bookstore
 * @subpackage auth
 * @author     Enkuso
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class authActions extends sfActions
{
    /**
     * Хэрэглэгч нэвтрэх (Signin)
     * - method POST
     * - input: username, password
     *
     * return json|xml|void
     */
    public function executeSignin($request)
    {
        $this->getResponse()->setHttpHeader('Content-Type', 'application/json', true);

        $user = $this->getUser();
        if ($user->isAuthenticated())
        {
            return $this->redirect('@homepage');
        }

        $this->form = new sfGuardFormSignin(array(), array(), false);

        if ($request->isMethod('post'))
        {

            $username = $request->getParameter('username', null);
            $password = $request->getParameter('password', null);

            $this->form->bind(array('username'=>$username, 'password'=>$password, 'remember'=>false));
            if ($this->form->isValid())
            {
                $values = $this->form->getValues();
                $token = $this->getUser()->apiAuth($values['user']);

                $this->stat = 'ok';
                $this->user = array(
                    'token' =>  $token,
                    'name'  =>  $this->getUser()->getName()
                );
            }
            else {
                $this->stat = 'fail';
                $this->error_code = 98;
                $this->error_msg = apiErrors::getErrorMessage($this->error_code);
            }
        } else {
            $this->getResponse()->setHeaderOnly(true);
            $this->getResponse()->setStatusCode(401);
            return sfView::NONE;
        }
    }

    /**
     * Хэрэглэгч гарах (Signout)
     * - method GET
     * - input: token
     *
     * return json_string
     */
    public function executeSignout($request)
    {
        if($request->hasParameter('token')){
            $token = $request->getParameter('token');
            Doctrine_Core::getTable('UserToken')
                ->createQuery('t')
                ->delete()
                ->where('t.user_id = ?', $this->getUser()->getGuardUser()->getId())
                ->andWhere('t.token = ?', $token)
                ->execute();
        }
        $this->getUser()->signOut();

        $this->getResponse()->setHttpHeader('Content-Type', 'application/json', true);

        $this->stat = 'ok';
    }

    /**
     * Хэрэглэгч бүртгүүлэх
     */
    public function executeSignup(sfWebRequest $request)
    {

        $this->form = new sfGuardRegisterForm(array(),array(),false);

        if ($request->isMethod('post'))
        {
            $this->getResponse()->setHttpHeader('Content-Type', 'application/json', true);

            $newuser = array(
                'username'      =>  $request->getParameter('username'),
                'email_address' =>  $request->getParameter('email'),
                'password'      =>  $request->getParameter('password'),
                'password_again' =>  $request->getParameter('password'),
                'first_name'    =>  $request->getParameter('firstname', ''),
                'last_name'     =>  $request->getParameter('lastname', ''),
            );
            $this->form->bind($newuser);
            if ($this->form->isValid())
            {
                $user = $this->form->save();
                $token = $this->getUser()->apiAuth($user);

                $this->stat = 'ok';
                $this->user =  array(
                    'token' =>  $token,
                    'name'  =>  $this->getUser()->getName()
                );
            } else {
                $this->stat = 'fail';
                $this->error_code = 90;
                if($this->form['username']->hasError())
                    $this->error_code = 91;
                if($this->form['email_address']->hasError())
                    $this->error_code = 92;
                $this->error_msg = apiErrors::getErrorMessage($this->error_code);
            }
        } else {
            $this->getResponse()->setHeaderOnly(true);
            $this->getResponse()->setStatusCode(401);
            return sfView::NONE;
        }
    }

    /**
     * Хэрэглэгч нууц үг сэргээх
     */
    public function executeForgotPassword(sfWebRequest $request)
    {
        $form = new sfForm(array(),array(),false);

        $form->setWidget('email', new sfWidgetFormInput());
        $form->setValidator('email', new sfValidatorEmail());
        $form->setValidator('email', new sfValidatorDoctrineChoice(array(
            'model'     => 'sfGuardUser',
            'column'    => 'email_address',
        )));

        if ($request->isMethod('post'))
        {
            $email = $request->getParameter('email', null);

            $form->bind(array('email'=>$email));
            if ($form->isValid())
            {
                # TODO: Send email to user

                $this->stat = 'ok';
            }
            else {
                $this->stat = 'fail';
                $this->error_code = 93;
                $this->error_msg = apiErrors::getErrorMessage($this->error_code);
            }
        } else {
            $this->getResponse()->setHeaderOnly(true);
            $this->getResponse()->setStatusCode(401);
            return sfView::NONE;
        }
    }
}
